#!/usr/bin/env python

import os
import pygame
import math

if not pygame.mixer:
	print "Warning, sound disabled!"

def load_png(name, alternate_path = None, scale = None):
	""" Load image and return image object """
	if alternate_path is None:
		fullname = os.path.join('data', name)
	else:
		fullname = os.path.join(os.path.expanduser(alternate_path), name)
		
	try:
		image = pygame.image.load(fullname)
		if image.get_alpha() is None:
			image = image.convert()
		else:
			image = image.convert_alpha()
	except pygame.error, message:
		print "Cannot load image:", fullname
		raise SystemExit, message
	
	if scale is not None:
		image = pygame.transform.scale(image, scale)
		
	return image, image.get_rect()
	
def load_constrained_png(name, path, max_width, max_height):
	fullname = os.path.join(os.path.expanduser(path), name)
	
	try:
		image = pygame.image.load(fullname)
	except pygame.error, message:
		print "Cannot load image:", fullname
		image = pygame.image.load(os.path.join("data", "arkaya.png"))

	if image.get_alpha() is None:
		image = image.convert()
	else:
		image = image.convert_alpha()

	image_width = float(image.get_width())
	image_height = float(image.get_height())
	aspect = image_width / image_height

	# could also just check on aspect > 1 etc.
	if image_width > max_width:
		image_width = int(math.floor(max_width))
		image_height = int(math.floor(image_width / aspect))
		image = pygame.transform.scale(image, (image_width, image_height))

	if image_height > max_height:
		image_height = int(math.floor(max_height))
		image_width = int(math.floor(image_height * aspect))
		image = pygame.transform.scale(image, (image_width, image_height))

	return image, image.get_rect()

def load_music(filename):
	""" Load mp3 for playback """
	fullname = os.path.join('data/sound', filename)
	try:
		sound = pygame.mixer.music.load(fullname)
	except pygame.error, message:
		print "Can't load sound:", ogg
		raise SystemExit, message
	return sound

def load_icon():
	icon = pygame.Surface((32, 32))
	icon.set_colorkey((0, 0, 0))
	rawicon = pygame.image.load(os.path.join("data", "icon.png"))
	for i in range(0, 32):
		for j in range(0, 32):
			icon.set_at((i, j), rawicon.get_at((i, j)))

	return icon
